package io.gitee.yth.design.pattern.test.core.pattern.behavioral.iterator;

import java.io.Serializable;
import java.util.AbstractCollection;
import java.util.Arrays;
import java.util.ConcurrentModificationException;
import java.util.EmptyStackException;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.RandomAccess;
import java.util.function.Consumer;

/**
 * @author yth
 * @since 2023-04-29-17:46
 */
public class MyStack<E> extends AbstractCollection<E>
        implements Cloneable, Serializable, RandomAccess {

    private static final long serialVersionUID = 114514L;

    private static final int DEFAULT_CAPACITY = 10;
    private static final int DEFAULT_SHRINK_CAPACITY_THRESHOLD = 512;
    private static final Object[] DEFAULT_EMPTY_ELEMENTS = new Object[]{};

    private Object[] elementData;
    private int size;
    private final int shrinkThreshold;
    private transient int modCount = 0;

    public MyStack() {
        elementData = DEFAULT_EMPTY_ELEMENTS;
        size = 0;
        shrinkThreshold = DEFAULT_SHRINK_CAPACITY_THRESHOLD;
    }

    public MyStack(int initialCapacity) {
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal Capacity: " + initialCapacity);
        elementData = new Object[initialCapacity];
        size = 0;
        shrinkThreshold = Math.max(DEFAULT_SHRINK_CAPACITY_THRESHOLD, initialCapacity);
    }

    private void ensureCapacity(int capacitySize) {
        if (capacitySize < 0)
            throw new OutOfMemoryError();
        capacitySize = (elementData != DEFAULT_EMPTY_ELEMENTS)
                ? capacitySize : DEFAULT_CAPACITY;
        if (elementData.length < capacitySize) {
            grow(capacitySize);
        }
    }

    private void grow(int minCapacity) {
        int oldCapacity = elementData.length;
        int newCapacity = oldCapacity + (oldCapacity >> 1);
        if (newCapacity < 0)
            newCapacity = Integer.MAX_VALUE;
        if (newCapacity < minCapacity)
            newCapacity = minCapacity;
        elementData = Arrays.copyOf(elementData, newCapacity);
    }

    private void tryShrink() {
        if (elementData.length > shrinkThreshold
                && size() < elementData.length << 3) {
            elementData = Arrays.copyOf(elementData, elementData.length << 1);
        }
    }

    public void push(E item) {
        modCount++;
        ensureCapacity(size + 1);
        elementData[size++] = item;
    }

    public E pop() {
        if (isEmpty())
            throw new EmptyStackException();
        modCount++;
        final E peek = peek();
        elementData[--size] = null; // help gc, eliminate obsolete reference
        tryShrink();
        return peek;
    }

    @SuppressWarnings("unchecked")
    private E elementData(int index) {
        return (E) elementData[index];
    }

    public E peek() {
        if (isEmpty())
            throw new EmptyStackException();
        return elementData(size - 1);
    }

    public E get(int index) {
        if (index < 0 || index >= size)
            throw new IndexOutOfBoundsException();
        return elementData(index);
    }

    public int size() {
        return size;
    }

    @Override
    public Object[] toArray() {
        return Arrays.copyOf(elementData, size);
    }

    @Override
    public <T> T[] toArray(T[] a) {
        if (a.length < size)
            // Make a new array of a's runtime type, but my contents:
            return (T[]) Arrays.copyOf(elementData, size, a.getClass());
        System.arraycopy(elementData, 0, a, 0, size);
        if (a.length > size)
            a[size] = null;
        return a;
    }

    @Override
    public boolean add(E e) {
        push(e);
        return true;
    }

    @Override
    public boolean remove(Object o) {
        if (!Objects.equals(o, peek())) {
            throw new UnsupportedOperationException();
        }
        pop();
        return true;
    }

    @Override
    public void clear() {
        size = 0;
    }

    @Override
    public Iterator<E> iterator() {
        return new StackItr();
    }

    @Override
    public MyStack<?> clone() {
        try {
            MyStack<?> clone = (MyStack<?>) super.clone();
            clone.elementData = Arrays.copyOf(elementData, size);
            clone.modCount = 0;
            return clone;
        } catch (CloneNotSupportedException e) {
            // this shouldn't happen, since we are Cloneable
            throw new AssertionError();
        }
    }

    private class StackItr implements Iterator<E> {
        private int cursor;       // index of next element to return
        private int lastRet = -1; // index of last element returned; -1 if no such
        private int expectedModCount = modCount;

        StackItr() {
        }

        public boolean hasNext() {
            return cursor != size;
        }

        @SuppressWarnings("unchecked")
        public E next() {
            checkForComodification();
            int i = cursor;
            if (i >= size)
                throw new NoSuchElementException();
            Object[] elementData = MyStack.this.elementData;
            if (i >= elementData.length)
                throw new ConcurrentModificationException();
            cursor = i + 1;
            return (E) elementData[lastRet = i];
        }

        @Override
        @SuppressWarnings("unchecked")
        public void forEachRemaining(Consumer<? super E> consumer) {
            Objects.requireNonNull(consumer);
            final int size = MyStack.this.size;
            int i = cursor;
            if (i >= size) {
                return;
            }
            final Object[] elementData = MyStack.this.elementData;
            if (i >= elementData.length) {
                throw new ConcurrentModificationException();
            }
            while (i != size && modCount == expectedModCount) {
                consumer.accept((E) elementData[i++]);
            }
            // update once at end of iteration to reduce heap write traffic
            cursor = i;
            lastRet = i - 1;
            checkForComodification();
        }

        final void checkForComodification() {
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
        }
    }
}
